const fs = require('fs');

function generateRandomArray() {
    const arr = [];
    for (let i = 0; i < 100; i++) {
        arr.push(Math.floor(Math.random() * 1000));
    }
    return arr;
}


function insertionSort(arr) {
    for (let i = 1; i < arr.length; i++) {
        let current = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] > current) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = current;
    }
    return arr;
}


function writeToFile(arr) {
    const str = arr.join(', ');
    fs.writeFile('output.txt', str, (err) => {
        if (err) throw err;
        console.log('已将排序后的数组写入output.txt文件');
    });
}

const randomArr = generateRandomArray();
console.log('生成的随机数组为：\n', randomArr);
const sortedArr = insertionSort(randomArr);
console.log('排序后的数组为：\n', sortedArr);
writeToFile(sortedArr);
